<?php

namespace app\common\model;

use app\index\model\Unionid;
use EasyWeChat\Factory;
use Picqer\Barcode\BarcodeGeneratorJPG;
use think\Db;
use think\Log;
use think\Model;


class VipCard extends Model
{

    // 表名
    protected $name = 'vip_card';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text'
    ];


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function getVipCard()
    {
        return self::where(['id' => 1])->find();
    }


    /*
    * 开通vip
    * */
    public function openVipCard($data_array)
    {
        // 获取开通会员的信息
        $vip = Db::name('vip_card')->where('id', $data_array['vip_id'])->find();
        // 调用config
        $config = config('wechat_pay');
        $app = Factory::payment($config);
        // 生成数据
        $end_time = time() + $vip['day'] * 86400;
        // 生成订单编号
        $order_id = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
        $data = [
            'order_id' => $order_id,
            'user_id' => $data_array['user_id'],
            'vip_id' => $vip['id'],
            'money' => $vip['price'],
            'status' => 1,
            'start_time' => time(),
            'end_time' => $end_time,
            'create_time' => time()
        ];
        $user = Db::name('user')->where('id', $data_array['user_id'])->field('money,openid')->find();

        Db::name('vip_card_order')->insert($data);
        $result = $app->order->unify([
            'body' => '开通会员卡' . $vip['price'] . '元',
            'out_trade_no' => $order_id,
            // 'response_type' => 'array',
            'total_fee' => $vip['price'] * 100,
            'notify_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/api/payCall/openVipCard',
            'trade_type' => 'JSAPI',
            'openid' => $user['openid'],
        ]);

        Log::write('https://' . $_SERVER['HTTP_HOST'] . '/api/payCall/openVipCard');
        $jssdk = $app->jssdk;
        $config = $jssdk->bridgeConfig($result['prepay_id'], false);
//            if ($result['return_code'] == "SUCCESS" && $result['return_msg'] == "OK"){
        if ($config) {
            return ['msg' => '开通成功', 'code' => 1, 'data' => $config];
        } else {
            return ['msg' => '开通失败', 'code' => 0, 'data' => $config];
        }

    }


    public function getCard($data_array)
    {
//        //查询会员卡
        $userCard = Db::name('user_card')->where(['member_id' => $data_array['user_id'], 'status' => 0])->find();
        if (!$userCard) {
            return ['msg' => '会员卡不存在', 'code' => 0];
        }
        //获取用户信息
//        $unionid = Db::name('unionid')->where(['user_id' => $data_array['user_id']])->find();
//        $openid = $unionid['w_openid'];
        $care_id = $userCard['card_id'];
        $data = $this->get_sign($care_id);
//        if (!$unionid['w_openid']) {
//            return ['msg' => '请先关注公众号', 'code' => 0];
//        }
        return ['msg' => '获取成功', 'code' => 1, 'data' => $data];
    }

    public function updateStatus($data_array)
    {
        $card_id = $data_array['card_id'] ?? '';
        $code = $data_array['code'] ?? '';
        //查询
        $user_card = Db::name('user_card')->where(['card_id' => $card_id])->find();
        if (!$user_card) {
            return ['msg' => '会员卡不存在', 'code' => 0];
        }
        if ($user_card['status'] == 1) {
            return ['msg' => '您已领取了会员卡', 'code' => 0];
        }

        //code解码
        $app = Factory::officialAccount(config('wx_program'));

        $res = $app->card->code->decrypt($code);
        $code = $res['code'];


        if (Db::name('user_card')->where(['card_id' => $card_id])->update(['status' => 1, 'code' => $code])) {
            return ['msg' => '获取成功', 'code' => 1];
        }
        return ['msg' => '领取失败', 'code' => 0];

    }


    public function getUserCard($data_array)
    {
        $url = config('fastadmin.api_url');
        $user_card = Db::name('user_card')->where(['member_id' => $data_array['user_id'], 'status' => 1])->find();
        if (!$user_card) {
            return ['msg' => '未开通会员', 'code' => 0];
        }
        $user = Db::name('user')->where(['id' => $data_array['user_id']])->field('id,avatar,nickname')->find();
        $user_card['vip_card_time'] = date("Y/m/d", $user_card['vip_card_time']);
        $user_card['avatar'] = $user['avatar'];
        $user_card['avatar'] = $user['avatar'] ? $url . $user['avatar'] : "";

        $user_card['nickname'] = $user['nickname'];
        //获取vip总次数 描述
        $vip = Db::name('vip_card')->where('id', '=', 1)->field('pay_goods_nums,content')->find();
        $user_card['vip_nums'] = $vip['pay_goods_nums'];
        $user_card['content'] = $vip['content'];
        return ['msg' => '获取成功', 'code' => 1, 'data' => $user_card];
    }


    public function request_Get($url)
    {
        $curl = curl_init();
        $timeout = 5;
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }


    public function getAccessToken()
    {
        $config = config('wx_program');
        $appid = $config['app_id'];
        $appsecret = $config['secret'];
        $access_token = $_COOKIE['access_token'] ?? '';
        if (!$access_token) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
            $access = json_decode($this->request_Get($url), true);
            setcookie("access_token", $access['access_token'], time() + 7200);
            $access_token = $access['access_token'];
            // print_r($access);
        }
        return $access_token;
    }


    /**
     * 获取卡券签名
     * @param $timestamp int 时间戳
     * @param $api_ticket string 卡券ticket
     * @param $noncestr string 随机字符串，由开发者设置传入，加强安全性（若不填写可能被重放请求）。随机字符串，不长于 32 位
     * @param $card_id string 卡券ID
     * @param $openid string 用户的微信小程序openid
     * * @param $code string 卡的编号
     * @return array
     */
    public function get_sign($card_id)
    {
        $arr = array();
        $nonceStr = $this->generateNonceStr();
        $apiTicket = $this->getCardApiTicket();
        $timestamp = (string)time();
        $arr['timestamp'] = $timestamp;
        $arr['nonce_str'] = $nonceStr;
        $arr['apiTicket'] = $apiTicket;
        $arr['card_id'] = $card_id;
//        $arr['openid'] = $openid;
        asort($arr, SORT_STRING); // 排序
        $key = implode($arr); // 加密

        $signature = sha1($key);
        return array(
            'timestamp' => $timestamp,
            'apiTicket' => $apiTicket,
//            'openid' => $openid,
            'card_id' => $card_id,
            'nonce_str' => $nonceStr,
            'signature' => $signature
        );
    }


    public function getCardApiTicket()
    {

        $api_ticket = $_COOKIE['ticket'] ?? '';
        if (empty($api_ticket)) {
            $token = $this->getAccessToken();  //上一步得到的access_token
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $token . "&type=wx_card";
            $api_ticket = $this->request_Get($url);
            $res = json_decode($api_ticket, true);
            setcookie("ticket", $res['ticket'], time() + 7200);
            $api_ticket = $res['ticket'];
        }
        return $api_ticket;
    }


    /**
     * 密码字符集
     * @param int $length
     * @return string
     */
    public function generateNonceStr($length = 16)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }


}
